﻿using AutoMapper;
using Microsoft.Data.SqlClient;
using SqlSugar;
using SX.BaseService.Repository.Core;
using SX.BaseService.Repository.Entity;
using SX.BaseService.Service.Interface;
using SX.Core;
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Threading.Tasks;

namespace SX.BaseService.Service.Implement.SysRole
{
    /// <summary>
    /// 角色管理服务
    /// </summary>
    public class SysRoleService :DbContext,ISysRoleService
    {
        private readonly IRepository<SysRoleEntity> _repository;
        private readonly IMapper _mapper;
        public SysRoleService(IRepository<SysRoleEntity> repository,IMapper mapper)
        {
            _mapper = mapper;
            _repository = repository;
        }
     
        public async Task<IApiResult> Add(RoleAddModel model)
        {
            var entity = _mapper.Map<SysRoleEntity>(model);
            entity.Id = GuidHelper.NewSequentialGuid();
            var res = await _repository.Add(entity);
            return ApiResult.Result(res > 0);
        }

        public async Task<IApiResult> Delete(List<string> ids)
        {
            var res = await Db.Deleteable<SysRoleEntity>().In(ids).ExecuteCommandAsync();
            return ApiResult.Result(res > 0);
        }

        public async Task<IApiResult> GetById(string id)
        {
            var entity = await Db.Queryable<SysRoleEntity>().Where(x => x.Id == id).FirstAsync();
            return ApiResult.Ok(entity);
        }

        public async Task<IApiResult> Query(RoleQueryModel model)
        {
            RefAsync<int> total = 0;
            var queryable = Db.Queryable<SysRoleEntity>();
            var source = await queryable
                .OrderBy(x => x.CreateTime, OrderByType.Desc)
                .ToPageListAsync(model.PageIndex, model.PageSize, total);
            PageResult<SysRoleEntity> result = new PageResult<SysRoleEntity>()
            {
                Rows = source,
                TotalCount = total
            };
            return ApiResult.Ok(result);
        }

        public async Task<IApiResult> Update(RoleUpdateModel model)
        {
            var entity = _mapper.Map<SysRoleEntity>(model);
            var res = await Db.Updateable(entity).IgnoreColumns(ignoreAllNullColumns: true, ignoreAllDefaultValue: true).ExecuteCommandAsync();
            return ApiResult.Result(res > 0);
        }
    }
}
